package com.qidian.zl.paper.servlets;

import com.qidian.zl.paper.dao.SelectorDAO;
import com.qidian.zl.paper.factory.ServiceFactory;
import com.qidian.zl.paper.pojo.Selector;
import com.qidian.zl.paper.service.SelectorService;
import com.qidian.zl.paper.util.JsonTools;
import com.qidian.zl.paper.util.StResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/selector/queryByFieldId")
public class SelectorServlet extends HttpServlet {
    private SelectorService selectorService = ServiceFactory.getSelectorSerice();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.endsWith("queryByFieldId")) {
            queryByFieldId(request, response);
        }
    }

    private void queryByFieldId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求参数
        StResult result = null;
        try {
            List<Selector> selectors = selectorService.queryByFieldId(Integer.parseInt(request.getParameter("fieldId")));
            result = StResult.ok(selectors);
        } catch (Exception e) {
            result = StResult.fail("查询失败");
        }
        // 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));
    }
}
